<template>
  <a-upload
    :data="state.headers"
    :action="state.uploadUrl"
    :before-upload="beforeUpload"
    :maxCount="props.maxCount"
    v-model:file-list="state.fileList"
    list-type="picture-card"
    @preview="handlePreview"
    @change="handleChange($event)"
    @remove="handelRemove"
    class="wf"
  >
    <div v-if="state.fileList < props.maxCount">
      <plus-outlined />
      <div style="margin-top: 8px">上传图片</div>
    </div>
  </a-upload>
  <a-modal :visible="state.previewVisible" :title="state.previewTitle" :footer="null" @cancel="handleCancel">
    <img alt="这是一张图片" style="width: 100%" :src="state.previewImage" />
  </a-modal>
</template>
<script setup>
import { PlusOutlined } from '@ant-design/icons-vue'
import { onMounted, watch } from '@vue/runtime-core'
import { message } from 'ant-design-vue'
import { reactive, defineProps, defineEmits } from 'vue'

import { upload_qiniu } from '../config/api'
import { UPLOAD_URL, QINIU_URL } from '../config/config'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

const props = defineProps({
  imgUrl: {
    type: String,
    default: () => {}
  },
  maxCount: {
    type: Number,
    default: 1
  },
  multiple: {
    type: Boolean,
    default: false
  } //是否可以多图上传
})

const emits = defineEmits(['upload', 'remove'])

watch(
  () => props.imgUrl,
  newVal => {
    handelshowPic(newVal)
  }
)

onMounted(() => {
  getToken()
})
const state = reactive({
  uploadUrl: UPLOAD_URL,
  fileList: [],
  headers: {
    token: ''
  },
  previewVisible: false,
  previewImage: '',
  previewTitle: ''
})

const handleCancel = () => {
  state.previewVisible = false
}
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj)
  }
  state.previewImage = file.url || file.preview
  state.previewVisible = true
  state.previewTitle = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
// 移出图片
const handelRemove = file => {
  state.fileList.forEach((item, index) => {
    if (item.uid == file.uid) {
      state.fileList.splice(index, 1)
    }
  })
  let img = state.fileList.length ? state.fileList : ''
  emits('remove', img)
  // console.log(state.fileList.length ? state.fileList : '')
}
// 回显图片
const handelshowPic = nval => {
  let json = {
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: nval
  }
  // state.fileList = [state.fileList, json]
  state.fileList = []
  state.fileList.push(json)
  console.log(state.fileList)
}
//
const handleChange = data => {
  let fileList = [...data.fileList]
  if (state.fileList <= props.maxCount) {
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.data.url
      }
      return file
    })
  }
  state.fileList = fileList
  if (data.file.status === 'uploading') {
    console.log('上传中')
  }
  if (data.file.status === 'done') {
    let img = QINIU_URL + state.fileList[0].response.key
    // console.log(QINIU_URL + state.fileList[0].response.key)
    emits('upload', img)
    // this.$emit('getFlieList', this.fileList[0].response.data)
  }
  if (data.file.status === 'error') {
    message.error('图片上传失败，请重试！！！')
  }
}
// 上传之前
const beforeUpload = file => {
  // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  // if (!isJpgOrPng) {
  //   this.$message.error('只能上传png或jpg格式的图片!')
  //   this.fileList = []
  //   return isJpgOrPng
  // }
  // const isLt2M = file.size / 1024 / 1024 < 2
  // if (!isLt2M) {
  //   this.fileList = []
  //   this.$message.error('图片尺寸不能超过 2MB!')
  //   return isLt2M
  // }
  // if (this.fileList.length == this.maxLength) {
  //   this.$message.error('最多只能上传' + this.maxLength + '图片')
  //   this.disabled = true
  // } else {
  //   this.disabled = false
  // }
}

//获取token
const getToken = async () => {
  const res = await upload_qiniu()
  state.headers.token = res.data
}
</script>
<style scoped lang="scss">

</style>
